import { defineComponent, inject } from 'vue'
import { dataTableContextKey } from './interface'
import { getColumnClassName, getRowClassName } from './utils'

import VirtualList from '../virtual-list'

const TableBody = defineComponent({
  setup(_, { slots }) {
    const { props, leftFixedColumsRef, rightFixedColumsRef, fixedColumnLeftMapRef, fixedColumnRightMapRef } = inject(dataTableContextKey)
    const { prefixCls } = props

    const itemsWrap = (_, { slots }) => (
      <div style={`width:${props.scrollX}px`}>
        <table class={`${prefixCls}_table`}>
          <tbody class={`${prefixCls}_tbody`}>{{ ...slots }}</tbody>
        </table>
      </div>
    )

    return () => {
      const { prefixCls, columns, data, rowProps, rowClass, virtualScroll } = props

      const rows = data.map((row, index) => {
        const cls = [`${prefixCls}_tr`, getRowClassName(rowClass, row, index)]
        const props = rowProps?.(row, index)
        return (
          <tr class={cls} key={row.key as string} {...props}>
            {columns.map((col, colIndex) => {
              const fixLast = col === leftFixedColumsRef.value[leftFixedColumsRef.value.length - 1],
                rightFirst = col === rightFixedColumsRef.value[0]
              const cls = {
                [`${prefixCls}_td`]: true,
                [getColumnClassName(col, colIndex)]: true,
                [`${prefixCls}_td-fix-${col.fixed}`]: col.fixed,
                [`${prefixCls}_td-fix-left-last`]: fixLast,
                [`${prefixCls}_td-fix-right-first`]: rightFirst,
                [`${prefixCls}_td-align-${col.align}`]: col.align
              }
              const style = {
                width: col.width + 'px',
                left: fixedColumnLeftMapRef.value[col.key] + 'px',
                right: fixedColumnRightMapRef.value[col.key] + 'px'
              }
              return (
                <td key={col.key} class={cls} style={style}>
                  {/* { col.render ? col.render(rowData, rowIndex) : rowData[col.key] } */}
                  {slots[col.key] ? slots[col.key]({ row, index }) : row[col.key]}
                </td>
              )
            })}
          </tr>
        )
      })

      return virtualScroll ? (
        <VirtualList class={`${prefixCls}_body`} items={rows} itemsWrap={itemsWrap} virtual itemKey='key' bufferSize={2}>
          {{ default: ({ item }) => item }}
        </VirtualList>
      ) : (
        <div class={`${prefixCls}_body`}>
          <itemsWrap>{rows}</itemsWrap>
        </div>
      )
    }
  }
})

export default TableBody
